<template>
  <div :id="id" class="bar-sty"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
  props: {
    data: {
      type: Array,
      default: () => {
        return []
      }
    },
    categoryData: {
      type: Array,
      default: () => {
        return []
      }
    },
    id: String
  },
  data() {
    return {
      myChart: null,
      chartDom: null
    }
  },
  computed: {
    bothArraysHaveValues() {
      return this.data.length > 0 && this.categoryData.length > 0;
    }
  },
  watch: {
    bothArraysHaveValues(newValue, oldValue) {
      if (newValue && !oldValue) {
        this.init();
      }
    }
  },
  mounted() {
    // 获取DOM元素，初始化Echarts图表对象，但不设置数据
    this.chartDom = document.getElementById(this.id);
    this.myChart = echarts.init(this.chartDom);
    if (this.data.length > 0 && this.categoryData.length > 0) {
      this.init();
    }
  },
  methods: {
    init() {
      const option = {
        tooltip: {
          show: true
        },
        grid: {
          show: false,
          left: "0%",
          bottom: "15%"
        },
        xAxis: {
          type: 'category',
          data: this.categoryData,
          axisTick: {
            show: false
          },
          axisLine: {
            show: false
          }
        },
        yAxis: [{
          type: "value",
          show: false
        }],
        series: [
          {
            barMinHeight: 10,
            barWidth: 18,
            data: this.data,
            type: 'bar',
            // 取消鼠标移入高亮
            emphasis: {
              disabled: true,
              focus: 'none'
            }
          }
        ]
      };
      this.myChart.setOption(option);
    }
  }
}
</script>

<style lang="less" scoped>
.bar-sty {
  width: 100%;
  height: 100%;
}
</style>